import 'package:dio/dio.dart';

class NetworkUtil {
  Dio? _dio;

  // must do init first
  void init({
    String? baseUrl,
    int connectTimeout = 200,
    int receiveTimeout = 200,
  }) {
    BaseOptions options = BaseOptions();
    if (baseUrl?.isNotEmpty == true) {
      options.baseUrl = baseUrl!;
    }

    _dio = Dio(options);
  }

  void dispose() {
    _dio?.close();
    _dio = null;
  }

  // throws exception
  Future<Map<String, dynamic>?> getHttp(
    String getUrl, {
    Map<String, dynamic>? params,
  }) async {
    try {
      Response? resp = await _dio?.get(getUrl, queryParameters: params);
      return resp?.data;
    } catch (e) {
      return null;
    }
  }

  // throws exception
  Future<Map<String, dynamic>?> postHttp(
    String postUrl, {
    Map<String, dynamic>? params,
  }) async {
    try {
      Response? resp = await _dio?.post(postUrl, queryParameters: params);
      return resp?.data;
    } catch (e) {
      return null;
    }
  }
}
